package cc.bluemc.modules.weixin.service;

import cc.bluemc.modules.weixin.entity.WxPublicAccountEntity;
import cc.bluemc.modules.weixin.entity.WxQrcordScanEntity;
import cc.bluemc.modules.weixin.entity.WxuserEntity;
import cc.bluemc.platform.springUtil.SpringConfigUtil;
import com.alibaba.fastjson.JSON;
import com.gson.bean.*;
import com.gson.inf.DefaultMessageProcessingHandlerImpl;
import com.gson.oauth.Authorize3p;
import com.gson.oauth.User;
import com.gson.token.Token;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;

public class MessageProcessingHandlerImpl extends DefaultMessageProcessingHandlerImpl{
	private static Logger logger = LoggerFactory.getLogger(MessageProcessingHandlerImpl.class);
	
	private MenuService menuService = (MenuService) SpringConfigUtil.getBean("menuService");
	
	private WxuserService wxuserService = (WxuserService) SpringConfigUtil.getBean("wxuserService");

	private WxPublicAccountService accountService = (WxPublicAccountService) SpringConfigUtil.getBean("wxPublicAccountService");

	private RedisTemplate redisTemplate = (RedisTemplate) SpringConfigUtil.getBean("redisTemplate");

	private WxQrcordScanService qrcordScanService = (WxQrcordScanService) SpringConfigUtil.getBean("wxQrcordScanService");

	//平台用户
	private  WeixinAccount weixinAccount=WeixinAccount.getWeixinAccount();


	@Override
	public void allType(InMessage msg, String appId) {
//		setOutMessage(menuService.home(msg,appId));
	}
	@Override
	public void textTypeMsg(InMessage msg,String appId) {
		setOutMessage(menuService.replyText(msg,appId));
	}
	@Override
	public void eventSubscribeTypeMsg(InMessage msg,String appId) {
		// 关注
		String qrParam=null;
		if (StringUtils.isNotBlank(msg.getEventKey()) && StringUtils.isNotBlank(msg.getTicket())) {
			// 扫描带参数二维码
			logger.debug("【事件】关注:扫描带参数二维码,用户OpenID:{}", msg.getFromUserName());
			String eventKey= msg.getEventKey();

			qrParam =StringUtils.removeStart(eventKey,"qrscene_");
			logger.info("二维码参数：{}",qrParam);
		}

		try {
			WxPublicAccountEntity accountEntity = accountService.get(appId);
			//获取公众号授权消息
			AuthorizationInfo authAccessToken = Authorize3p.getAuthAccessToken(weixinAccount,appId,accountEntity.getAuthorizerRefreshToken());
			//从微信服务器拿到微信用户信息
			UserInfo userInfo = User.getUserInfo(authAccessToken.getAuthorizer_access_token(), msg.getFromUserName());

			logger.info("用户关注["+appId+"]\r\n"+ JSON.toJSONString(userInfo));
			//TODO houfengli 2017/2/23 16:13 微信关注,保存用户信息
			//微信关注,保存用户信息
			WxuserEntity wxuser= wxuserService.getByOpenidAndAppId(msg.getFromUserName(),appId);
			if(null==wxuser){
				wxuser = new WxuserEntity(userInfo);
				wxuser.setAppid(appId);
			}
			wxuser.setOpenid(msg.getFromUserName());
			wxuser.setSubscribe(1);
			wxuser.setSubscribe_time(new Date());
			wxuserService.saveOrUpdate(wxuser);


			WxQrcordScanEntity scan = new WxQrcordScanEntity();
			scan.setScanTime(new Date());
			scan.setOpenid(msg.getFromUserName());
			scan.setSubscribe("0");
			scan.setAppid(appId);
			if(StringUtils.isNotBlank(qrParam)){
				//存入redis，供WeixinQrCodeEntryAction注册、登录、绑定绑定使用后删除
				scan.setParam(qrParam);
			}
			qrcordScanService.save(scan);
		} catch (Exception e) {
			logger.error("用户关注处理事件异常",e);
		}

//		setOutMessage(menuService.home(msg,appId));
	}
	@Override
	public void eventUnsubscribeTypeMsg(InMessage msg,String appId) {
		try {
			WxuserEntity wxuser= wxuserService.getByOpenidAndAppId(msg.getFromUserName(),appId);
			if(null!=wxuser){
				wxuser.setSubscribe(0);
				wxuser.setUnsubscribeTime(new Date());
				wxuserService.update(wxuser);
			}
		} catch (Exception e) {
			logger.error("修改用户取消关注失败",e);
		}
	}
	@Override
	public void eventScanTypeMsg(InMessage msg, String appId) {
		logger.info("关注用户：{}，扫描二维码", msg.getFromUserName());
		String eventKey= msg.getEventKey();
		WxQrcordScanEntity scan = new WxQrcordScanEntity();
		scan.setScanTime(new Date());
		scan.setOpenid(msg.getFromUserName());
		scan.setSubscribe("1");
		scan.setAppid(appId);
		if(StringUtils.isNotBlank(eventKey)){
			//存入redis，供WeixinQrCodeEntryAction注册、登录、绑定绑定使用后删除
			scan.setParam(eventKey);
		}
		try {
			qrcordScanService.save(scan);
		} catch (Exception e) {
			logger.error("保存用户扫描二维码异常",e);
		}
//		setOutMessage(menuService.home(msg,appId));
	}
	@Override
	public void eventClickTypeMsg(InMessage msg,String appId) {
		logger.info("【事件】点击菜单拉取消息,appId:" + appId);
		if (StringUtils.isBlank(msg.getEventKey())) {
			setOutMessage(null);
			return;
		}
		String cmd = msg.getEventKey().toLowerCase();
		if ("home".equals(cmd)) {
			logger.info("查看首页主菜单");
			setOutMessage(menuService.home(msg,appId));
			return;
		} 
	}
	@Override
	public void eventViewTypeMsg(InMessage msg,String appId) {
		logger.info("【事件】菜单跳转链接,appId:" + appId);
//		setOutMessage(menuService.home(msg,appId));
	}


	/**
	 * 第三方平台每隔10分钟推送一次ticke，
	 *
	 * @param ticket
	 */
	@Override
	public void component_verify_ticketTypeMsg(InMessage ticket,String appId) {
		logger.info("第三方平台推送ticket："+ticket.getComponentVerifyTicket());
		Token.cache(Token.TokenType.wx3p_component_verify_ticket, weixinAccount, ticket.getComponentVerifyTicket());
		setOutMessage(new TextOutMessage("success"));
	}

	/**
	 * 取消授权，
	 *
	 * @param ticket
	 */
	@Override
	public void unauthorizedTypeMsg(InMessage ticket,String appId) {
		try {
			logger.info("取消授权："+ticket.getAuthorizerAppid());
			WxPublicAccountEntity accountEntity = new WxPublicAccountEntity();
			accountEntity.setAppid(ticket.getAuthorizerAppid());
			accountService.delete(accountEntity);
		} catch (Exception e) {
			logger.error("取消授权异常，AuthorizerAppid："+ticket.getAuthorizerAppid(),e);
		}
	}

	/**
	 * 更新授权
	 *
	 * @param ticket
	 */
	@Override
	public void updateauthorizedTypeMsg(InMessage ticket,String appId) {
//		super.updateauthorizedTypeMsg(ticket,appId);
	}

	/**
	 * 授权成功通知
	 *
	 * @param ticket
	 */
	@Override
	public void authorizedTypeMsg(InMessage ticket,String appId) {
		logger.info("授权成功通知,AuthorizerAppid："+ticket.getAuthorizerAppid());
	}

	@Override
	public void eventLocationTypeMsg(InMessage msg,String appId) {
	}
	@Override
	public void afterProcess(InMessage inMessage, OutMessage outMessage) {
	}
}
